﻿<%@ WebHandler Language="C#" Class="fileupload" %>

using System;
using System.Web;
using System.IO;
using System.Text;
using EasyFMS.Common;
using Liger.Data;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;

public class fileupload : IHttpHandler
{
    public static DbContext DB = DbHelper.Db;

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Clear();
        FileUpLoad(context);
        context.Response.Flush();
        context.Response.End();
    }

    /// <summary>
    /// 获取对应导入设置
    /// </summary>
    /// <param name="setType"></param>
    /// <returns></returns>
    public Dictionary<string, Dictionary<string,string>> GetSet(string setType)
    {
        Dictionary<string, Dictionary<string, string>> temp = new Dictionary<string, Dictionary<string, string>>();
        Dictionary<string, string> sqlStr = new Dictionary<string, string>();
        Dictionary<string, string> columnStr = new Dictionary<string, string>();
        string tempSqlStr = "INSERT INTO DBO." + setType + "(";
        sqlStr.Clear();
        DataSet setSet = DB.ExecuteDataSet("SELECT [ColumnCode],[ColumnName],[TableCode],[TableName],[ExcelColumn],[FieldType],[UserCreateID],[CreateDate] FROM dbo.dImportSet WHERE TableCode = '" + setType + "' ORDER BY ExcelColumn");
        if (setSet.Tables[0].Rows.Count >= 1)
        {
            for (int i = 0; i < setSet.Tables[0].Rows.Count; i++)
            {
                tempSqlStr += setSet.Tables[0].Rows[i]["ColumnCode"].ToString() + ",";
                columnStr.Add(setSet.Tables[0].Rows[i]["ExcelColumn"].ToString(), setSet.Tables[0].Rows[i]["FieldType"].ToString());
            }
            tempSqlStr += "UserCreateID,CreateDate)";
            sqlStr.Add("sql",tempSqlStr);
            temp.Add("sql", sqlStr);
            temp.Add("column", columnStr);
        }
        else
        {
            temp.Clear();
        }
        return temp;
    }

    public void FileUpLoad(HttpContext context)
    {
        try
        {
            string uploadtype = context.Request.Form["uploadtype"].ToString();
            context.Response.Charset = "utf-8";
            HttpPostedFile file = context.Request.Files["Filedata"];
            if (uploadtype == "Attachment")
            {
                Stream myStream = file.InputStream;
                int DataLen = file.ContentLength;
                string filename = Path.GetFileName(file.FileName);
                string filetype = Path.GetExtension(file.FileName);
                byte[] Data = new byte[DataLen];
                myStream.Read(Data, 0, DataLen);
                myStream.Close();
                if (Data.Length > 0)
                {
                    string updateSql = "UPDATE dbo.cInstead SET Doc = @image,IsDoc = 1 ,DocName = @filename WHERE UID = @uid ";
                    SqlCommand myCmd = new SqlCommand(updateSql, new SqlConnection(DB.Db.ConnectionString));
                    myCmd.Parameters.Add("@image", SqlDbType.Image).Value = Data;
                    myCmd.Parameters.Add("@filename", SqlDbType.NVarChar, 50).Value = filename;
                    myCmd.Parameters.Add("@uid", SqlDbType.Int).Value = context.Request.Form["uid"].ToString();
                    if (myCmd.Connection.State == ConnectionState.Closed)
                        myCmd.Connection.Open();
                    try
                    {
                        myCmd.ExecuteNonQuery();
                        context.Response.Write("OK");
                    }
                    catch (Exception sss) { }
                    finally
                    {
                        myCmd.Connection.Close();
                    }
                }
                else
                {
                    context.Response.Write("ER||没有数据需要上传");
                }
            }
            else
            {
                Dictionary<string, Dictionary<string, string>> importSet = new Dictionary<string, Dictionary<string, string>>();
                importSet = GetSet(uploadtype);
                if (importSet.Count > 0)
                {
                    int userid = Convert.ToInt32(context.Request.Form["userid"].ToString());
                    DB.ExecuteDataSet("DELETE FROM " + uploadtype + " WHERE UserCreateID = " + userid.ToString());
                    int rowVal = ExcelHelper.RenderToDb(file.InputStream, importSet["sql"]["sql"].ToString(), importSet["column"], userid);
                    if (rowVal > 0)
                    {
                        DataSet infoSet = new DataSet();
                        switch (uploadtype)
                        {
                            case "ZINVOICE":
                                infoSet = DB.ExecuteDataSet("EXEC [dbo].[pImportInvoice] " + userid + "");
                                break;
                            case "ZCOST":
                                infoSet = DB.ExecuteDataSet("EXEC [dbo].[pImportCost] " + userid + "");
                                break;
                            case "ZBANKLIST":
                                infoSet = DB.ExecuteDataSet("EXEC [dbo].[pImportBankList] " + userid + "");
                                break;
                            default:
                                break;
                        }
                        context.Response.Write("OK");
                    }
                    else
                    {
                        context.Response.Write("ER||数据导入出错");
                    }
                }
                else
                {
                    context.Response.Write("ER||没有数据");
                }
            }
        }
        catch (Exception sss)
        {
            context.Response.Write("ER||" + sss.Message);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}